import customtkinter as ctk
import tkinter as tk
from tkinter import ttk


class OrdersTab(ctk.CTkFrame):
    ORDER_STATUS_MAP = {
        '0': '询价',
        '1': '待付款',
        '2': '已付款待发货',
        '3': '已发货待确认',
        '4': '已发货已收货'
    }

    def __init__(self, parent):
        super().__init__(parent)
        self.current_page = 1
        self.is_refreshing = False
        self.order_index = {}
        self.ORDER_REFRESH_INTERVAL = 10
        self.on_refresh = None
        self.on_prev = None
        self.on_next = None
        self.on_row_activated = None
        self._init_ui()

    def _init_ui(self):
        self.pack(fill='both', expand=True)
        ctk.CTkLabel(self, text='订单列表').pack(anchor='w', padx=10, pady=(10, 0))

        table_frame = ctk.CTkFrame(self)
        table_frame.pack(fill='both', expand=True, padx=10, pady=10)

        columns = ('买家名称', '电影名称', '影院名称', '影厅名称', '放映时间', '状态', '操作')
        self.tree = ttk.Treeview(table_frame, columns=columns, show='headings')
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=120, anchor='center')
        vsb = ttk.Scrollbar(table_frame, orient='vertical', command=self.tree.yview)
        self.tree.configure(yscrollcommand=vsb.set)
        self.tree.bind('<Double-1>', self._on_double_click)
        self.tree.pack(side='left', fill='both', expand=True)
        vsb.pack(side='right', fill='y')

        ctrlRow = ctk.CTkFrame(self)
        self.auto_refresh_var = tk.BooleanVar(value=True)
        self.autoRefreshCheck = ctk.CTkCheckBox(ctrlRow, text=f'自动刷新({self.ORDER_REFRESH_INTERVAL}秒)', variable=self.auto_refresh_var)
        self.autoRefreshCheck.pack(side='left', padx=10, pady=10)

        self.refreshBtn = ctk.CTkButton(ctrlRow, text='刷新订单', command=lambda: self.on_refresh and self.on_refresh())
        self.refreshBtn.pack(side='left', padx=10, pady=10)

        self.prevBtn = ctk.CTkButton(ctrlRow, text='上一页', command=lambda: self.on_prev and self.on_prev())
        self.prevBtn.pack(side='left', padx=10, pady=10)

        self.pageLabel = ctk.CTkLabel(ctrlRow, text='第 1 页')
        self.pageLabel.pack(side='left', padx=10, pady=10)

        self.nextBtn = ctk.CTkButton(ctrlRow, text='下一页', command=lambda: self.on_next and self.on_next())
        self.nextBtn.pack(side='left', padx=10, pady=10)

        ctrlRow.pack(fill='x', padx=10)

    def set_page_text(self, text: str):
        self.pageLabel.configure(text=text)

    def set_refreshing(self, flag: bool):
        self.is_refreshing = flag
        self.refreshBtn.configure(state='disabled' if flag else 'normal', text='刷新中...' if flag else '刷新订单')

    def update_orders(self, orders):
        for item in self.tree.get_children():
            self.tree.delete(item)
        self.order_index = {}
        for order in orders:
            buyer_nickname = order.get('buyer_nickname', '未知')
            film_name = order.get('film_name', '未知')
            cinema_name = order.get('cinema_name', '未知')
            hall_name = order.get('hall_name', '未知')
            show_time = order.get('show_time', '未知')
            status = order.get('state', 0)
            if isinstance(status, int):
                status_str = self.ORDER_STATUS_MAP.get(str(status), f'未知状态({status})')
            elif isinstance(status, str) and status.isdigit():
                status_str = self.ORDER_STATUS_MAP.get(status, f'未知状态({status})')
            else:
                status_str = '未知状态'
            action_text = '发货' if status_str == '已付款待发货' else '查看'
            iid = self.tree.insert('', 'end', values=(buyer_nickname, film_name, cinema_name, hall_name, show_time, status_str, action_text))
            self.order_index[iid] = order

    def _on_double_click(self, event):
        sel = self.tree.selection()
        if not sel:
            return
        iid = sel[0]
        order = self.order_index.get(iid)
        if order and callable(self.on_row_activated):
            self.on_row_activated(order)

